package com.aishua.aishuawallet.mina;

import android.content.Context;
import android.util.Log;


import org.apache.mina.core.session.IoSession;



class Task implements Runnable {

    private String requestString;
    private  ConnectionManager mManager;
    private IoSession session;
    private Context mContext;

    Task(Context mContext, String requestString, ConnectionManager mManager) {

		this.requestString = requestString;
		this.mContext =mContext;
		this.mManager = mManager;
    }


    @Override
    public void run() {

        while (true) {

            session = mManager.connnect();

            if (null != session) {
                Log.e("tag", "连接成功");
                writeToServer(requestString);
                break;
            }
            try {
                Log.e("tag", "尝试重新连接");
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }


    public void writeToServer(Object msg) {

        if (session != null) {
            Log.e("tag", "客户端准备发送消息");
            session.write(msg);
        }
    }


    public void closeSession() {

        if (session != null) {
            session.closeOnFlush();
        }
    }

    public void removeSession() {

        this.session = null;
    }

    /**
     * 断开连接
     */
    public void disContect() {

        mManager.disContect();

        Log.e("tag", "断开连接");


    }

}
